//
//  PDFDownloadViewController.m
//  PDFDownload
//
//  Created by guyu on 13-12-2.
//  Copyright (c) 2013年 gavin. All rights reserved.
//

#import "PDFDownloadViewController.h"

@interface PDFDownloadViewController ()

@end

@implementation PDFDownloadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self juHua];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

//加载菊花显示
- (void)juHua{
    _indicator = (UIActivityIndicatorView *)[self.view viewWithTag:103];
    
    	if (_indicator == nil) {
            //初始化:
            UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
            indicator.tag = 103;
            //设置显示样式,见UIActivityIndicatorViewStyle的定义
            indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
            //设置背景色
            indicator.backgroundColor = [UIColor clearColor];
            //设置背景透明
            indicator.alpha = 1;
            //设置背景为圆角矩形
            indicator.layer.cornerRadius = 6;
            indicator.layer.masksToBounds = YES;
            //设置显示位置
            [indicator setCenter:CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0)];
            //开始显示Loading动画
            [indicator startAnimating];
            [self.view addSubview:indicator];
        	}
    	//开始显示Loading动画
    	[_indicator startAnimating];
}
// 设置关闭菊花
- (IBAction)stopJuHua:(id)sender {
    UIActivityIndicatorView *indicator = (UIActivityIndicatorView *)[self.view viewWithTag:103];

    //停止显示Loading动画
    [indicator stopAnimating];
}


- (void)downloadPDF{
    //设置下载文件保存的目录
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString* _filePath = [paths objectAtIndex:0];
    
    //File Url
    NSString* fileUrl = @"http://.../...pdf";
    
    //Encode Url 如果Url 中含有空格，一定要先 Encode
    fileUrl = [fileUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    
    //创建 Request
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:fileUrl]];
    NSString* fileName = @"down_form.pdf";
    NSString* filePath = [_filePath stringByAppendingPathComponent:fileName];
    
    //下载进行中的事件
    //使用AF进行下载
    AFURLConnectionOperation *operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
    
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        //下载的进度，如 0.53，就是 53%
        float progress =   (float)totalBytesRead / totalBytesExpectedToRead;
        
        //下载完成
        //该方法会在下载完成后立即执行
        if (progress == 1.0) {
//            [downloadsTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }];
    
    
    //下载完成的事件
    //该方法会在下载完成后 延迟 2秒左右执行
    //根据完成后需要处理的及时性不高，可以采用该方法
    [operation setCompletionBlock:^{
        
    }];
    
    [operation start];
}

/*
 
 查看 PDF 文件
 
 IOS 下查看 PDF 文件的方法是蛮多的，但是 WebView 最简单便捷，虽然不是最强大的。
 
 */
- (void)readPDF{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString* filePath = [paths objectAtIndex:0];
    
    NSString* fileName = @"down_form.pdf";
    NSString *path = [filePath stringByAppendingPathComponent:fileName];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
    if (fileExists) {
//        path = [Util urlEncodeString:path];
        NSURL* url = [[NSURL alloc]initWithString:path];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
//        [webView loadRequest:request];
    }
}

@end
